package com.fansl.allround.common.core.validator;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

/**
 * @author fansl
 * @Description: 校验不为null
 * @date 2019/9/20 15:00
 */
public class NotNullValidator extends ValidatorHandler<Object> implements Validator<Object> {

    private String fieldName;

    public NotNullValidator(String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public boolean validate(ValidatorContext context, Object s) {
        boolean validateFlag = true;
        validateFlag = !(null == s||s.equals(null)&&validateFlag);
        if(s instanceof String){
            if(StrUtil.isBlank(((String) s).trim())&&validateFlag){
                validateFlag = false;
            }
        }
        if(!validateFlag){
            context.addError(ValidationError.create(String.format("%s不能为空！", fieldName))
                    .setErrorCode(-1)
                    .setField(fieldName)
                    .setInvalidValue(s));
            return validateFlag;
        }
        return true;
    }

}
